package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.entity.*;
import cn.xuewenbao.edu.entity.vo.MyLikedVo;
import cn.xuewenbao.edu.entity.vo.MyFavoriteVo;
import cn.xuewenbao.edu.entity.vo.MyLikeOrFavoriteContentVo;
import cn.xuewenbao.edu.mapper.LikeContentMapper;
import cn.xuewenbao.edu.service.*;
import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.entity.MemberData;
import cn.xuewenbao.ucenter.service.MemberDataService;
import cn.xuewenbao.ucenter.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.handler.IFillRuleHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 点赞表 服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-04-21
 */
@Service
public class LikeContentServiceImpl extends ServiceImpl<LikeContentMapper, LikeContent> implements LikeContentService {

    @Autowired
    private LikeContentMapper likeContentMapper;
    @Autowired
    private MemberDataService memberDataService;
    @Autowired
    private ColumnTypeService columnTypeService;
    @Autowired
    private ColumnDataService columnDataService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private BookService bookService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private JournalSubjectService journalSubjectService;

    @Autowired
    private JournalService journalService;

    @Autowired
    private MemberService memberService;

    @Override
    public Result<?> likeContent(String contentId, String userId, String columnType, String authorId) {
        //判断是否已经点赞
        QueryWrapper<LikeContent> likeContentQueryWrapper = new QueryWrapper<>();
        likeContentQueryWrapper.eq("user_id", userId).eq("content_id", contentId).eq("column_type", columnType);
        LikeContent likeContent = baseMapper.selectOne(likeContentQueryWrapper);
        if (likeContent != null) {
            return Result.error("重复点赞");
        }
        //添加点赞记录
        likeContent = new LikeContent();
        likeContent.setContentId(contentId);
        likeContent.setUserId(userId);
        likeContent.setColumnType(columnType);
        likeContent.setAuthorId(authorId);
        baseMapper.insert(likeContent);
        //点赞者 likeCount+1
        QueryWrapper<MemberData> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        MemberData memberData = memberDataService.getOne(wrapper);
        if (memberData == null) {   //用户数据为空, 初始化用户数据
            Boolean addSuccess = memberDataService.addMemberData(userId, 1L, 0L, 0L, 0L, 0L);
            if (!addSuccess) {
                return Result.error("点赞者的用户数据初始化失败");
            }
        } else {
            memberData.setLikeCount(memberData.getLikeCount() + 1);
            memberDataService.updateById(memberData);
        }
        //被点赞者 likedCount加一
        //获取作者id, 根据内容id和类型
        List<String> authorIdList = this.getAuthorIdList(contentId, columnType);
        if (authorIdList == null || authorIdList.size() == 0) {
            return Result.error("获取作者id失败");
        }
        //修改获赞数, 根据作者id
        QueryWrapper<MemberData> wrapper2 = new QueryWrapper<>();
        for (String id : authorIdList) {
            wrapper2.clear();
            wrapper2.eq("user_id", id);
            MemberData likedMemberData = memberDataService.getOne(wrapper2);
            if (likedMemberData == null) {
                Boolean addSuccess = memberDataService.addMemberData(userId, 0L, 1L, 0L, 0L, 0L);
                if (!addSuccess) {
                    return Result.error("获赞者用户数据初始化失败");
                }
            } else {
                likedMemberData.setLikedCount(likedMemberData.getLikedCount() + 1);
                memberDataService.updateById(likedMemberData);
            }
        }
        //内容数据表点赞数加一
        QueryWrapper<ColumnData> columnDataQueryWrapper = new QueryWrapper<>();
        columnDataQueryWrapper.eq("content_id", contentId).eq("column_type", columnType);
        ColumnData columnData = columnDataService.getOne(columnDataQueryWrapper);
        if (columnData == null) {
            Boolean addSuccess = columnDataService.addColumnData(contentId, columnType, 1L, 0L, 0L, 0L);
            if (!addSuccess) {
                return Result.error("内容数据初始化失败");
            }
        } else {
            columnData.setLikeCount(columnData.getLikeCount() + 1);
            columnDataService.updateById(columnData);
        }
        return Result.OK("点赞成功", null);
    }

    @Override
    public Result<?> likeList(String userId, String columnType) {
        //查找用户在columnType专栏下的点赞记录
        List<MyFavoriteVo> voList = new ArrayList<>();
        QueryWrapper<LikeContent> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("column_type", columnType);
        List<LikeContent> likeList = baseMapper.selectList(wrapper);
        //根据每一条点赞记录, 获取更全的vo信息
        for (LikeContent likeContent : likeList) {
            //获取 MyFavoriteVo的 contentId userId columnType
            MyFavoriteVo vo = new MyFavoriteVo();
            BeanUtils.copyProperties(likeContent, vo);
            vo.setColumnType(columnType);
            //获取 MyFavoriteVo的 title cover viewCount
            String tableName = columnTypeService.getColumnTypeById(columnType);
            if (tableName == null) {
                return Result.error("点赞内容的类型columnType不正确");
            }
            MyLikeOrFavoriteContentVo contentVo = columnTypeService.selectMyLikeOrFavoriteContent(likeContent.getContentId(), tableName);
            if (contentVo == null) {    //根据点赞记录, 原内容查找不到 (已删除)
                continue;   //查找下一个点赞记录
            }
            BeanUtils.copyProperties(contentVo, vo);    //soure不能为 null
            //获取 MyFavoriteVo的 likeCount favoriteCount commentCount;
            QueryWrapper<ColumnData> columnDataWrapper = new QueryWrapper<>();
            columnDataWrapper.eq("content_id", likeContent.getContentId()).eq("column_type", columnType);
            ColumnData data = columnDataService.getOne(columnDataWrapper);
            if (data == null) { //根据点赞记录, 原内容的数据查找不到 (已删除)
                continue;   //查找下一个点赞记录
            }
            BeanUtils.copyProperties(data, vo);
            //获取 MyFavoriteVo的 commentCount isLike isFavorite;
            Long count = commentService.getCommentCount(likeContent.getContentId(), columnType);
            vo.setCommentCount(count);
            boolean isFavorite = favoriteService.hasFavoriteOne(userId, likeContent.getContentId(), columnType).isSuccess();
            vo.setIsFavorite(isFavorite);
            boolean isLike = hasLikeOne(userId, likeContent.getContentId(), columnType).isSuccess();
            vo.setIsLike(isLike);
            voList.add(vo);
        }
        return Result.OK("获取点赞列表成功！", voList);
    }

    @Override
    public Result<?> dislikeContent(String contentId, String userId, String columnType) {
        //删除点赞记录
        QueryWrapper<LikeContent> wrapperLike = new QueryWrapper<>();
        wrapperLike.eq("user_id", userId).eq("content_id", contentId).eq("column_type", columnType);
        int update = baseMapper.delete(wrapperLike);
        if (update < 1) {
            return Result.error("点赞表中没有该记录");
        }
        //点赞的用户点赞数减一
        QueryWrapper<MemberData> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        MemberData memberData = memberDataService.getOne(wrapper);
        if (memberData == null) {
            return Result.error("用户数据表中未找到该用户");
        }
        if (memberData.getLikeCount() < 1) {
            return Result.error("用户数据表中数据出错");
        }
        memberData.setLikeCount(memberData.getLikeCount() - 1);
        memberDataService.updateById(memberData);
        //被点赞的的获赞数减一
        //获取作者id, 根据内容id和类型
        List<String> authorIdList = this.getAuthorIdList(contentId, columnType);
        if (authorIdList == null || authorIdList.size() == 0) {
            return Result.error("获取作者id失败");
        }
        //修改获赞数, 根据作者id
        QueryWrapper<MemberData> wrapper2 = new QueryWrapper<>();
        for (String id : authorIdList) {
            wrapper2.clear();
            wrapper2.eq("user_id", id);
            MemberData likedMemberData = memberDataService.getOne(wrapper2);
            if (likedMemberData == null) {
                return Result.error("用户数据表中未找到作者");
            }
            if (likedMemberData.getLikedCount() < 1) {
                return Result.error("用户数据表中的作者数据出错");
            }
            likedMemberData.setLikedCount(likedMemberData.getLikedCount() - 1);
            memberDataService.updateById(likedMemberData);
        }
        //内容数据表点赞数减一
        QueryWrapper<ColumnData> columnDataQueryWrapper = new QueryWrapper<>();
        columnDataQueryWrapper.eq("content_id", contentId).eq("column_type", columnType);
        ColumnData columnData = columnDataService.getOne(columnDataQueryWrapper);
        if (columnData == null) {
            return Result.error("内容数据表中未找到信息");
        }
        if (columnData.getLikeCount() < 1) {
            return Result.error("内容数据表中的数据出错");
        }
        columnData.setLikeCount(columnData.getLikeCount() - 1);
        columnDataService.updateById(columnData);
        return Result.OK("取消点赞成功", null);
    }

    public List<String> getAuthorIdList(String contentId, String columnTypeId) {
        String tableName = columnTypeService.getColumnTypeById(columnTypeId);
        if (tableName == null) {
            return null;
        }
        //获取作者id, 根据专栏类型和内容id
        List<String> authorIdList = new ArrayList<>();
        if ("journal_subject".equals(tableName)) {  //期刊的作者有多个
            String authorId = likeContentMapper.getJournalUserId(contentId);
            authorIdList.addAll(Arrays.asList(authorId.split(",")));
        } else {
            String fieldName = null;   //被点赞的用户编号(userId)在不同表中的字段名称不同
            switch (tableName) {
                case "article":
                case "book":
                    fieldName = "user_id";
                    break;
                case "course":
                    fieldName = "teacher_id";
                    break;
            }
            String authorId = likeContentMapper.getUserId(contentId, tableName, fieldName);
            authorIdList.add(authorId);
        }
        return authorIdList;
    }

    @Override
    public Result<?> hasLikeOne(String userId, String contentId, String columnType) {
        Result<Boolean> result = new Result<>();
        QueryWrapper<LikeContent> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("content_id", contentId).eq("column_type", columnType);
        LikeContent likeContent = baseMapper.selectOne(wrapper);
        if (likeContent == null) {
            result.setSuccess(false);
            result.setMessage("该用户未点赞目标内容");
            result.setResult(false);
        } else {
            result.setSuccess(true);
            result.setMessage("已点赞");
            result.setResult(true);
        }
        return result;
    }

    //得到该作者的昨天的点赞量
    @Override
    public Result<Map<String, Long>> getLastLikeCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到前一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String lastDay = formatter.format(calendar.getTime());
        String start = "2021-01-01 00:00:00";
        String end = lastDay + " 23:59:59";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<LikeContent> wrapper = new QueryWrapper<>();
        try {
            wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
            wrapper.eq("author_id", userId);
        } catch (ParseException e) {
            log.error(e.toString());
        }
        Map<String, Long> map = new HashMap<>();
        map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        result.setResult(map);
        return result;
    }

    //得到该作者的一周的点赞量
    @Override
    public Result<Map<String, Long>> getWeekLikeCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        Map<String, Long> map = new HashMap<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到一周的点赞量
        for (int i = 1; i <= 7; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String lastDay = formatter.format(calendar.getTime());
            String start = "2021-01-01 00:00:00";
            String end = lastDay + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<LikeContent> wrapper = new QueryWrapper<>();
            try {
                wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
                wrapper.eq("author_id", userId);
            } catch (ParseException e) {
                log.error(e.toString());
            }
            map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        }
        result.setResult(map);
        return result;
    }

    @Override
    public Result<Map<String, Long>> getMonthCount(String userId) {
        Result<Map<String, Long>> result = new Result<>();
        Map<String, Long> map = new HashMap<>();
        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //得到一周的点赞量
        for (int i = 1; i <= 30; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String lastDay = formatter.format(calendar.getTime());
            String start = "2021-01-01 00:00:00";
            String end = lastDay + " 23:59:59";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            QueryWrapper<LikeContent> wrapper = new QueryWrapper<>();
            try {
                wrapper.between("gmt_create", sdf.format(sdf.parse(start)), sdf.format(sdf.parse(end)));
                wrapper.eq("author_id", userId);
            } catch (ParseException e) {
                log.error(e.toString());
            }
            map.put(lastDay, Long.valueOf(baseMapper.selectCount(wrapper)));
        }
        result.setResult(map);
        return result;
    }

    //点赞表-获取我的获赞列表
    @Override
    public Result<List<MyLikedVo>> likedUserList(String userId) {
        Result<List<MyLikedVo>> result = new Result<>();
        List<MyLikedVo> myLikedVoList = new ArrayList<>();
        QueryWrapper<LikeContent> likeContentQueryWrapper = new QueryWrapper<>();
        likeContentQueryWrapper.eq("author_id",userId).orderByDesc("gmt_create");
        List<LikeContent> likeContents = baseMapper.selectList(likeContentQueryWrapper);

        for (LikeContent likeContent : likeContents) {
            MyLikedVo myLikedVo = new MyLikedVo();
            BeanUtils.copyProperties(likeContent, myLikedVo);
            if (likeContent.getColumnType().equals("1")){
                Article article = articleService.getById(likeContent.getContentId());
                if (article == null) {
                    continue;   //点赞的内容缺失，访问下一个点赞记录
                }
                myLikedVo.setTitle(article.getTitle());
                myLikedVo.setCover(article.getCover());
            }else if (likeContent.getColumnType().equals("2")){
                Course course = courseService.getById(likeContent.getContentId());
                if (course == null) {
                    continue;   //点赞的内容缺失，访问下一个点赞记录
                }
                myLikedVo.setTitle(course.getTitle());
                myLikedVo.setCover(course.getCover());
            }else if (likeContent.getColumnType().equals("3")){
                JournalSubject journalSubject = journalSubjectService.getById(likeContent.getContentId());
                if (journalSubject == null) {
                    continue;   //点赞的内容缺失，访问下一个点赞记录
                }
                myLikedVo.setTitle(journalSubject.getSubTitle());
                if (journalSubject.getParentId() == null) {
                    continue;
                }
                Journal parentJournal = journalService.getById(journalSubject.getParentId());
                if (parentJournal == null){
                    continue;
                }
                myLikedVo.setCover(parentJournal.getCover());
            }else {
                Book book = bookService.getById(likeContent.getContentId());
                if (book == null) {
                    continue;   //点赞的内容缺失，访问下一个点赞记录
                }
                myLikedVo.setTitle(book.getTitle());
                myLikedVo.setCover(book.getCover());
            }
            Member member = memberService.getById(likeContent.getUserId());
            if (member == null) {
                continue;   //点赞的用户缺失，访问下一个点赞记录
            }
            myLikedVo.setUsername(member.getUsername());
            myLikedVo.setAvatar(member.getAvatar());
            myLikedVoList.add(myLikedVo);
        }
        result.setResult(myLikedVoList);
        result.setSuccess(true);
        return result;
    }

}